cc.Class({
    extends: cc.Component,

    properties: {
        //标头
        labTopTitle:{
            default: null,
            type: cc.Label
        },
        //投注信息
        labShowAmount:{
           default: null,
           type: cc.Label 
        },

        //说明
        labDec:{
           default: null,
           type: cc.RichText 
        },

        edMutipleNum:{
            default:null,
            type:cc.EditBox
        },

        edIssueNum:{
            default:null,
            type:cc.EditBox
        },

        //选择球根目录
        betContent:{
            default:null,
            type:cc.Node
        },

        //投注单根目录
        ndBetPanle:{
            default: null,
            type: cc.Node
        },

        //选择球
        tgRedBall:{
            default: null,
            type: cc.Prefab
        },
        //设胆球
        tgChangeBall: {
            default:null,
            type:cc.Node
        },

        //选择玩法按钮列表
        tgAnySelList:{
            default:[],
            type:cc.Toggle
        },

        //机选清空切换按钮
        tgSelect:{
            default:null,
            type:cc.Toggle
        },

        //红球图片
        spRedBall:{
            default: null,
            type: cc.SpriteFrame
        },

        //黄球图片
        spYellowBall:{
            default: null,
            type: cc.SpriteFrame
        },

        //红球放大
        spBigRedBall:{
            default: null,
            type: cc.Sprite
        },

        //黄球放大
        spBigYellowBall:{
            default: null,
            type: cc.Sprite
        },

        tgIsStop:{
            default:null,
            type:cc.Toggle
        },

        ndAddAward:{
            default:[],
            type:cc.Node
        },

        BASEMONEY:2,//基础投资
        _rules:[],//规则
        _nums:[],//数值
        _decContents:[],//说明列表
        _betToggleList:[],//球指针列表
        _selRedBall:[],//选择球数字列表
        _selYellowBall:[],//选择胆球数字列表

        _isMiss:false,//是否开启遗漏
        _lotteryID:0,//彩种id
        _totalisuse:0,//总期数
        _isNorm:1,//当前模式0胆拖1标准
        _curMoney:0,
        _curBetNum:0,
        _curPage:2,
        _offsetX:0,//偏移x
        _offsetY:0,//偏移y
        _isStops:-1,//追号到截止
        _betManage:null//通用方法s
    },

    initConfig:function(){
        this._rules = [DEFINE.LOTTERYRULE115.ANYTWO,DEFINE.LOTTERYRULE115.ANYTHREE,DEFINE.LOTTERYRULE115.ANYFOUR,
                      DEFINE.LOTTERYRULE115.ANYFIVE,DEFINE.LOTTERYRULE115.ANYSIX,DEFINE.LOTTERYRULE115.ANYSEVEN,
                      DEFINE.LOTTERYRULE115.ANYEIGHT];

        this._nums = ["01","02","03","04","05","06","07","08","09","10","11"]; 
        this._isNorm = 1;
        this._decContents = [
            "<color=#ffffff>至少选2个号码，猜对任意2个开奖号即中</c><color=#fcd346>6元</color>",
            "<color=#ffffff>至少选3个号码，猜对任意3个开奖号即中</c><color=#fcd346>19元</color>",
            "<color=#ffffff>至少选4个号码，猜对任意4个开奖号即中</c><color=#fcd346>78元</color>",
            "<color=#ffffff>至少选5个号码，猜对全部5个开奖号即中</c><color=#fcd346>540元</color>",
            "<color=#ffffff>至少选6个号码，选号包含5个开奖号即中</c><color=#fcd346>90元</color>",
            "<color=#ffffff>至少选7个号码，选号包含5个开奖号即中</c><color=#fcd346>26元</color>",
            "<color=#ffffff>至少选8个号码，选号包含5个开奖号即中</c><color=#fcd346>9元</color>",
        ];
        this.names = ["任选二","任选三","任选四","任选五","任选六","任选七","任选八"];
        this._totalisuse = 87;
        this._betManage = cc.find("Canvas").getChildByName("ChatRoomPage").getChildByName("BetManage").getComponent("BetManage");
        this._offsetX = -380;
        this._offsetY =500;
        this._isStops =-1;
    },

    initReset:function(){
        if(this._isMiss)
            this._betManage.showMiss(this._betToggleList,this._lotteryID,this._lotteryID+this._rules[this._curPage-2].toString());
    },

    onLoad: function () {
        this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
                var contentRect = this.ndBetPanle.getBoundingBoxToWorld();
                contentRect.x = contentRect.x -20;
                contentRect.width = 1080;
                var touchLocation = event.getLocation();
                if(cc.rectContainsPoint(contentRect, touchLocation) == false){//关闭投注界面
                    this.onClose();
                }
        }, this);

       this.initPanel();
    },

    showAddAward:function(data){
        for(var i=0;i<data.length;i++)
        {
            var codestr = data[i].PlayCode.toString();
            var code = codestr.substring(codestr.length-2,codestr.length);
            var index = this._rules.indexOf(code); 
            if(index != -1)
            {
                var icode = parseInt(code);
                this.ndAddAward[icode-1].active = true;
            }
        }
    },

    init:function(lotteryid){
        this._lotteryID = lotteryid;
        this._isStops = -1;
        this.initConfig();
    },

      //是否中奖后停止追号
    onIsStops:function(toggle, customEventData){
        if(toggle.isChecked == true)
        {
            this._isStops = 0;
        }
        else
        {
            this._isStops = -1;
        }
    },

    initPanel:function(){
        for(var j = 0;j<this._nums.length;j++)
        {      
            var ball = cc.instantiate(this.tgRedBall);
            ball.getComponent('Bet_toggle_ball').init({
                num: this._nums[j],
                miss: ""
            });
            var checkEventHandler = new cc.Component.EventHandler();
            checkEventHandler.target = this.node; 
            checkEventHandler.component = "11X5AnySelectPage"
            checkEventHandler.handler = "onClickCallback";
            checkEventHandler.customEventData = j+1;
            ball.getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
            this.betContent.addChild(ball);
            this._betToggleList.push(ball);

            //事件监听
            //当手指在目标节点区域内离开屏幕时。
            ball.on(cc.Node.EventType.TOUCH_END, function (event) {
                event.stopPropagation();
               
                if(this._isNorm == 0)
                {
                    this.spBigYellowBall.node.y = 10000;
                }
                else
                {
                    this.spBigRedBall.node.y = 10000;
                }
            },this);

            //当手指在目标节点区域外离开屏幕时。
            ball.on(cc.Node.EventType.TOUCH_CANCEL, function (event) {
                event.stopPropagation();
               
                if(this._isNorm == 0)
                {
                    this.spBigYellowBall.node.y = 10000;
                }
                else
                {
                    this.spBigRedBall.node.y = 10000;
                }
            },this);

            //当手指触摸到屏幕时。
            ball.on(cc.Node.EventType.TOUCH_START, function (event,customEventData) {
                event.stopPropagation();
                var curTg = event.getCurrentTarget();
                var touchLocation = event.getLocation();
                if(ball.active != true)
                {
                    return;
                }
                if(this._isNorm == 0)
                {
                    this.spBigYellowBall.node.getChildByName("labnum").getComponent(cc.Label).string = curTg.getComponent('Bet_toggle_ball').getNum();
                    this.spBigYellowBall.node.x = curTg.x+this._offsetX;
                    this.spBigYellowBall.node.y = curTg.y+this._offsetY;
                }
                else
                {
                    this.spBigRedBall.node.getChildByName("labnum").getComponent(cc.Label).string = curTg.getComponent('Bet_toggle_ball').getNum();
                    this.spBigRedBall.node.x = curTg.x+this._offsetX;
                    this.spBigRedBall.node.y = curTg.y+this._offsetY;
                }
            },this);

            //当鼠标在目标节点在目标节点区域中移动时，不论是否按下。
            ball.on(cc.Node.EventType.MOUSE_MOVE, function (event) {
                event.stopPropagation();
               
                var curTg = event.getCurrentTarget();
                var contentRect = curTg.getBoundingBoxToWorld();
                var touchLocation = event.getLocation();
                if(cc.rectContainsPoint(contentRect, touchLocation) == false){        
                    if(this._isNorm == 0)
                    {
                        this.spBigYellowBall.node.y = 10000;
                    }
                    else
                    {
                        this.spBigRedBall.node.y = 10000;
                    }
                }  
            },this);

            //当手指在屏幕上目标节点区域内移动时。
            ball.on(cc.Node.EventType.TOUCH_MOVE, function (event) {
                event.stopPropagation();
                
                var curTg = event.getCurrentTarget();
                var contentRect = curTg.getBoundingBoxToWorld();
                var touchLocation = event.getLocation();
                if(cc.rectContainsPoint(contentRect, touchLocation) == false){
                    if(this._isNorm == 0)
                    {
                        this.spBigYellowBall.node.y = 10000;
                    }
                    else
                    {
                        this.spBigRedBall.node.y = 10000;
                    }
                }  
            },this);
         }

        var checkEventHandler = new cc.Component.EventHandler();
        checkEventHandler.target = this.node; 
        checkEventHandler.component = "11X5AnySelectPage"
        checkEventHandler.handler = "onChangeBallCallback";
        checkEventHandler.customEventData = "";
        this.tgChangeBall.getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
        this.tgChangeBall.active = false;


        for(var i=0;i<this.tgAnySelList.length;i++)
        {
            var checkEventHandler = new cc.Component.EventHandler();
            checkEventHandler.target = this.node; 
            checkEventHandler.component = "11X5AnySelectPage"
            checkEventHandler.handler = "onSelPageCallBack";
            checkEventHandler.customEventData = {
                name:this.names[i],
                hasNorm:(i==0||i==1||i==this.tgAnySelList.length-1)?1:0,
                pageID:i+2,
                decContent:this._decContents[i]
            };
            this.tgAnySelList[i].getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
        }
        //初始选择第一个小界面
        var temp = this.tgAnySelList[0].getComponent(cc.Toggle).checkEvents[0].customEventData;
        this.onSelPageCallBack(this.tgAnySelList[0],temp);
    },

    onSelPageCallBack:function(toggle, customEventData){
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this.labTopTitle.string = customEventData.name;
            this.labDec.string = customEventData.decContent;
            var hasNorm = customEventData.hasNorm;
            this._curPage = customEventData.pageID;

            if(hasNorm == 0)
            {
                this.tgChangeBall.active = true;
            }
            else
            {
                this.tgChangeBall.active = false;
            }
            this.clearCurSel();
        
        }
    },

    onClickCallback:function(toggle, customEventData){
        var num = customEventData;
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            if(this._isNorm == 0)//胆拖
            { 
                var maxNum = this._curPage-1;
                if(this._selYellowBall.length >= maxNum)
                {
                    ComponentsUtils.showTips("胆码最多只能选择"+maxNum.toString()+"个");
                    toggle.getComponent(cc.Toggle).isChecked = false;
                    return;
                }
                this._selYellowBall.push(num);
                toggle.checkMark.spriteFrame = this.spYellowBall;  
                toggle.getComponent("Bet_toggle_ball").setType(2);
                this.updateTgSelect();
                this.checkBet();
                return;
            }
            else if(this._isNorm == 1)
            {
                this._selRedBall.push(num);
                toggle.checkMark.spriteFrame = this.spRedBall;
                toggle.getComponent("Bet_toggle_ball").setType(1);
                this.updateTgSelect();
                this.checkBet();
                return;
            }
        }

        var type = toggle.getComponent("Bet_toggle_ball").getType();
        if(type == 1)
        {
            Utils.removeByValue(this._selRedBall,num);
        }
        else if(type == 2)
        {
            Utils.removeByValue(this._selYellowBall,num);
        }
        toggle.getComponent("Bet_toggle_ball").setType(0);
        this.updateTgSelect();
        this.checkBet();
    },

    updateTgSelect:function(){
        if(this._selRedBall.length>0 || this._selYellowBall.length>0)
        {
            this.tgSelect.getComponent(cc.Toggle).isChecked = true;
        }
        else
        {
            if(this._isNorm == 1)
            {
                this.tgSelect.getComponent(cc.Toggle).isChecked = false;
            }
            else
            {
                this.tgSelect.getComponent(cc.Toggle).isChecked = true;
            }
        } 
    },

    onChangeBallCallback:function(toggle){
       if(toggle.getComponent(cc.Toggle).isChecked)
       {
            this._isNorm = 0;
            ComponentsUtils.showTips("开始胆拖投注");
       }
       else
       {
            this._isNorm = 1;
       }
       this.updateTgSelect();
    },

    //设置金额
    setMoney:function(mon){
        this._curMoney = mon;
    },

    //得到金额
    getMoney:function(){
        return this._curMoney;
    },

    //设置注数
    setBetNum:function(num){
        this._curBetNum = num;
    },

    //得到注数
    getBetNum:function(){
        return this._curBetNum;
    },

    //设置期数
    setIssueNum:function(num){
        if(this._totalisuse >= parseInt(num))
        {
            this.edIssueNum.string = num;
        }
        else
        {
            ComponentsUtils.showTips("最大只能选择87期");
            this.edIssueNum.string = this._totalisuse.toString();
        }
        this.checkBet();
    },

    //得到期数
    getIssueNum:function(){
        var num = parseInt(this.edIssueNum.string);
        if(isNaN(num)){ 
            return 1;
        }else{
            return num;
        }        
    },

       //手动期数
    onEditBoxIssueChanged:function(editbox) {
        if(!Utils.isInt(editbox.string))
        {
            ComponentsUtils.showTips("输入格式错误！");
            editbox.string = "1";
        }
        if(editbox.string == null || editbox.string == "")
        {
            editbox.string = "1";
            ComponentsUtils.showTips("期数不能为空！");
        }

        var amount = parseInt(editbox.string);
        if(isNaN(amount) || amount<=0 ){
            editbox.string = "1";
        }
  
       this.setIssueNum(editbox.string);
    },

    //设置倍数
    setMutipleAmount:function(mutiple){
         this.edMutipleNum.string = mutiple;
         this.checkBet();
    },

    //获取当前倍数
    getMutipleAmount:function(){
        var amount = parseInt(this.edMutipleNum.string);
        if(isNaN(amount)){ 
            return 1;
        }else{
            return amount;
        }        
    },

    //手动倍数
    onEditBoxMutipleChanged:function(editbox) {
        if(!Utils.isInt(editbox.string))
        {
            ComponentsUtils.showTips("输入格式错误！");
            editbox.string = "1";
        }
        if(editbox.string == null || editbox.string == "")
        {
            editbox.string = "1";
            ComponentsUtils.showTips("倍数不能为空！");
        }

        var amount = parseInt(editbox.string);
        if(isNaN(amount) || amount > 999 || amount<=0 ){
            editbox.string = "1";
        }
  
        this.checkBet();
    },

    //显示投注信息
    setShowAmount:function(mut,bet){
        var issue = this.getIssueNum();
        var money = mut*bet*this.BASEMONEY*issue;
        this.setMoney(money);
        this.setBetNum(bet);
        this.labShowAmount.string = "共"+bet+"注"+ mut +"倍"+ issue + "期"+ money+"元";
    },

    //重置界面
    clearAllBetRecord:function(){
        this.clearCurSel();
    },

    //计算投注规则
    checkBet: function(){
        var bet = 0;
        if(this._selYellowBall.length>0)
        {
             //胆码
            var dan = this._selYellowBall.length;
            //拖码
            var tuo = this._selRedBall.length;
            if(dan <1 || tuo <1)
                bet = 0
            else    
                bet = LotteryUtils.combination(tuo,this._curPage-dan);
           
            if(bet == 1)
            {
                cc.log("胆拖2注起投");
                bet = 0;
            }
        }
        else
        {
             bet = LotteryUtils.combination(this._selRedBall.length,this._curPage);
        }
 
        var muiple = this.getMutipleAmount();
        this.setShowAmount(muiple,bet);
    },

    //投注信息组合
    dataToJson:function(){
        var obj = new Object(); 
        obj.PlayCode = parseInt(this._lotteryID + this._rules[this._curPage-2].toString()); 
        var nums = "";
        var num = "";
        if(this._selYellowBall.length>0)
        {
            var ball1 = this._selRedBall;
            var ball2 = this._selYellowBall;
            Utils.sortNum(ball1);
            Utils.sortNum(ball2);
            for(var i = 0;i<ball2.length;i++)
            {
                if(num != "")
                {
                    num+=",";
                }  
                num += ball2[i]>9 ? ball2[i].toString():"0"+ball2[i].toString();
            }
            nums = num;
            num = "";
            for(var i = 0;i<ball1.length;i++)
            {
                if(num != "")
                {
                    num+=",";
                }  
                var oneNum = ball1[i]>9 ? ball1[i].toString():"0"+ball1[i].toString(); 
                num += oneNum;
            }
            nums = nums + "#" + num;   
        }
        else
        {
            var ball = this._selRedBall;
            Utils.sortNum(ball);
            for(var i = 0;i<ball.length;i++)
            {
                if(nums != "")
                {
                    nums+=",";
                }  
                var oneNum = ball[i]>9 ? ball[i].toString():"0"+ball[i].toString(); 
                nums += oneNum;
            }
        }
  
        var arry = [];
        var numArrays = {
                "Multiple":this.getMutipleAmount(),
                "Bet":this.getBetNum(),
                "isNorm":this._isNorm,
                "Number":nums
            };
        arry.push(numArrays);
        obj.Data = arry;
        var json = JSON.stringify(obj);
        cc.log("提交订单：" + json);
        return json;
    },

     //追号组合支付
    chasePay:function(){
        var recv = function(ret){
            ComponentsUtils.unblock(); 
            if(ret.Code === 0)
            {
                var len = ret.Data.length;
                if(len != this.getIssueNum())
                {
                    this.setIssueNum(len);
                    this.setShowAmount();
                }
                var obj = new Object(); 
                obj.Stops = this._isStops;
                obj.IsuseCount = len;
                obj.BeginTime = ret.Data[0].BeginTime;
                obj.EndTime = ret.Data[len-1].EndTime;
                var arry = [];
                for(var i=0;i<ret.Data.length;i++)
                {
                    var numArrays = {
                        "IsuseID":ret.Data[i].IsuseCode,
                        "Amount": LotteryUtils.moneytoClient(this.getMoney()/this.getIssueNum()),//每期金额
                        "Multiple":this.getMutipleAmount(),//每期总倍数
                    };
                    arry.push(numArrays);
                }
                obj.Data = arry;
                var json = JSON.stringify(obj);

                var data = {
                    lotteryId:this._lotteryID,//彩种id
                    dataBase:this.dataToJson(),//投注信息
                    otherBase:json,//追号
                    money:this.getMoney(), 
                    buyType: this.getIssueNum() >1?1:0,//追号
                }

                window.Notification.emit("BET_ONPAY",data);
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);
            }
        }.bind(this);
        var data = {
            Token:User.getLoginToken(),
            LotteryCode:this._lotteryID,
            Top:this.getIssueNum(),
        }
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETADDTOISUSE, data, recv.bind(this),"POST");   
        ComponentsUtils.block();    
    },

   //付款
    onPayBtn:function(){
        if(this.getMoney() <= 0)
            return;
        
        if(this.getIssueNum()<=1)
        {
            var data = {
                lotteryId:this._lotteryID,//彩种id
                dataBase:this.dataToJson(),//投注信息
                otherBase:"",//追加
                money:this.getMoney(),
                buyType: 0,//追号
            }
            window.Notification.emit("BET_ONPAY",data);
        }
        else
        {
            this.chasePay();
        }

    },

    //清空当前选择
    clearCurSel:function(){
        this._selRedBall.length = 0;
        this._selYellowBall.length = 0;
        for(var i=0;i<this._betToggleList.length;i++)
        {
            this._betToggleList[i].getComponent(cc.Toggle).isChecked = false;
        }
        
        this.spBigYellowBall.node.y = 10000;
        this.spBigRedBall.node.y = 10000;
        this._isNorm = 1;
        this._isStops = -1;
        this.tgIsStop.getComponent(cc.Toggle).isChecked = false;
        this.tgSelect.getComponent(cc.Toggle).isChecked = false;
        this.tgChangeBall.getComponent(cc.Toggle).isChecked = false;
        this.setIssueNum(1);
        this.setMutipleAmount(1);
        this.checkBet();
    },

    //机选
    randomSelectCallBack:function(){   
        if(this._isNorm == 1)
        {
            this.clearCurSel();
            var randomArray = Utils.getRandomArrayWithArray(this._betToggleList, this._curPage);
            for(var j = 0; j<randomArray.length; j++){
                randomArray[j].getComponent(cc.Toggle).isChecked = true;
                var temp = randomArray[j].getComponent(cc.Toggle).checkEvents[0].customEventData;
                this.onClickCallback(randomArray[j].getComponent(cc.Toggle),temp);
            }
            return true;
        }
        return false;
    },

    //选择清空切换
    onSelectCallBack:function(toggle){
        if(this._isNorm == 0)
        {
            toggle.getComponent(cc.Toggle).isChecked = true;
            this.clearCurSel();
        }
        else
        {
            if(toggle.getComponent(cc.Toggle).isChecked)
            {
                this.randomSelectCallBack();
            }
            else
            {
                this.clearCurSel();
            }
        }
    },

    onClose:function(){
        window.Notification.emit("BET_ONCLOSE","");
    },

    onNextPage:function(){
        window.Notification.emit("BET_NEXTPAGE",1);
    },

    onLastPage:function(){
        window.Notification.emit("BET_NEXTPAGE",-1);
    },

    onMiss:function(toggle){
        if(this._isMiss && toggle.getComponent(cc.Toggle).isChecked)
            return;
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this._isMiss = true;
            this._betManage.showMiss(this._betToggleList,this._lotteryID,this._lotteryID+this._rules[this._curPage-2].toString());
        }    
        else
        {
            this._isMiss = false;
            this._betManage.setMiss(false,this._betToggleList,"");
        }
    },


});